using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel.Channels;
using System.Text;

namespace Weever.Json.Binding
{
    class JsonMessageEncoder: MessageEncoder
    {
        private string _contentType;
        private string _mediaType;
        private MessageVersion _messageVersion;

        public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                string data = reader.ReadToEnd();
                Console.WriteLine(data);
                return Message.CreateMessage(MessageVersion.None, "Action", data);
            }
        }

        public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
        {
            byte[] bytes = new byte[buffer.Array.Length];
            Array.Copy(buffer.Array, bytes, bytes.Length);
            bufferManager.ReturnBuffer(bytes);

            return ReadMessage(new MemoryStream(bytes), int.MaxValue, contentType);
        }

        public override void WriteMessage(Message message, Stream stream)
        {
            StreamWriter writer = new StreamWriter(stream);
            JsonWriter js = new JsonWriter(writer);
            js.BeginObject(); // envelope
            
            js.BeginObject("h"); // header
            js.WriteProperty("a", message.Headers.Action);
            js.EndObject(); // header

            js.WriteProperty("b", message.GetBody<string>());
            
            js.EndObject();
            writer.Flush();
        }

        public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager,
                                                        int messageOffset)
        {
            MemoryStream stream = new MemoryStream();
            string data = message.GetBody<string>();
            byte[] bytes = Encoding.UTF8.GetBytes(data);

            int totalLength = bytes.Length + messageOffset;
            byte[] totalBytes = bufferManager.TakeBuffer(totalLength);
            Array.Copy(bytes, 0, totalBytes, messageOffset, bytes.Length);
            return new ArraySegment<byte>(totalBytes, messageOffset, bytes.Length);
        }

        public override string ContentType
        {
            get { return _contentType; }
        }

        public override string MediaType
        {
            get { return _mediaType; }
        }

        public override MessageVersion MessageVersion
        {
            get { return _messageVersion; }
        }
    }
}
